// pages/detail/detail.js
const ctx = wx.createCanvasContext('credit-canvas');
let QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
let ajax = require('../../utils/ajax.js');
let qqmapsdk;
let user = require('../../utils/user.js');
user.isLogin();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatar: '/images/myDevice.png',
    loginStatus: '已登录',
    showModalStatus: false,
    characteristicId: "0000FFE1-0000-1000-8000-00805F9B34FB", // 监听characteristicId
    serviceId: "0000FFE0-0000-1000-8000-00805F9B34FB", // 监听serviceId
    location: '', // 定位城市
    update_time: '', // 更新时间
    temperature: 0, //温度
    quality: '', // 空气质量
    wind: '', // 风力风向
    outPM: '', // 车外PM
    canvasWidth: 0,
    canvasHeight: 0,
    currentNum: 0, // 初始化空气数值
    voice: 1, // 是否有声音
    voiceImg: '/images/voice_has.png',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let vm = this;
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'SBSBZ-XXIKV-4RMP5-UOIIJ-TMPIF-SJBGJ'
    });
    wx.getSystemInfo({
      success: function(res) {
        // console.dir(res)
        vm.setData({
          screenWidth: res.screenWidth
        })
      },
    })


    wx.createSelectorQuery().select(".credit-canvas").boundingClientRect(function(rect) {
      vm.setData({
        canvasWidth: rect.width,
        canvasHeight: rect.height
      })
    }).exec()
    // 16进制转10进制
    function ab2hex(buffer) {
      // console.log(buffer);
      const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function(bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('')
    }
    // 监听蓝牙BLE值变化事件
    wx.onBLECharacteristicValueChange(function(res) {
      // console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`);
      // console.log(res);
      let value = ab2hex(res.value),
        xx = parseInt(value.substring(18, 20), 16),
        yy = parseInt(value.substring(20, 22), 16),
        result = xx * 256 + yy;
      // console.log(value, xx, yy, 'result', result);
      if (result > 0) {

        vm.setData({
          currentNum: result
        });
        vm.drawCredit();
      }
    })
    console.log('Loading...');
    wx.getStorage({
      key: 'current_device',
      success: function(res) {
        console.log(res.data.deviceId);
        vm.getServices(res.data.deviceId);
      },
      fail: function() {
        console.log(arguments);
      },
    })
    vm.getLocation();
    wx.getStorage({
      key: 'voice',
      success: function(res) {
        console.log(res);
        vm.setData({
          voice: res.data,
          voiceImg: res.data > 0 ? '/images/voice_has.png' : '/images/voice_none.png',
        })
        vm.voiceRadio({}, res.data > 0 ? true : false);
      },
      fail: function(res) {
        wx.setStorage({
          key: 'voice',
          data: 1,
          success: function() {
            vm.setData({
              voice: 1,
              voiceImg: '/images/voice_has.png',
            })
            vm.voiceRadio({}, true);
          },
        });

      }
    })


  },
  voiceRadio: function(e, radio) {
    let vm = this,
      open = '01060000006609E0',
      off = '01060000000089ca',
      hex = null,
      deviceId = wx.getStorageSync('current_device').deviceId;
      console.log(vm);
    if (typeof radio != 'undefined') {
      console.log('has Radio:'+radio);
      radio = radio > 0 ? true : false;
    } else {
      console.log('hasn\'t Radio:' + vm.data.voice);
      radio = vm.data.voice > 0 ? false : true;
    }
    hex = radio ? open : off;
    wx.setStorageSync('voice', radio ? 1 : 0);
    vm.setData({
      voice: radio ? 1 : 0,
      voiceImg: radio ? '/images/voice_has.png' : '/images/voice_none.png'
    });
    // 16进制转ArrayBuffer
    const typeArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
      return parseInt(h, 16)
    }));
    var buffer = typeArray.buffer;
    console.log(radio);
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: vm.data.serviceId,
      characteristicId: vm.data.characteristicId,
      value: buffer,
      success: function(res) {
        console.log(res);
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },

  onReady: function() {
    this.drawCredit();
  },

  onShow: function() {
    this.timeout = setTimeout(this.drawCredit, 100);
  },


  // 我的设备
  myDeviceTap() {
    wx.navigateTo({
      url: '../myDevice/myDevice',
    })
  },
  // 跳转公用方法
  navigateTo: function(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url,
    });
  },
  // 退出
  loginOutTap() {
    let vm = this;
    wx.showModal({
      title: '提示',
      content: '退出登录，确认？',
      confirmColor: '#2aa146',
      success: function(res) {
        if (res.confirm) {
          ajax.requestPost(ajax.ajaxUrl() + 'member/logout', {}, 'post', '', function(res) {
            console.log(res);
            if ('SUCCESS' === res.status) {
              wx.setStorageSync('token', '');
              wx.setStorageSync('member', null);
              wx.showToast({
                title: '退出成功',
                icon: 'none',
                duration: 1500,
                success: function(res) {
                  wx.redirectTo({
                    url: '/pages/login/login',
                  })
                },
              })
            }
          }, function(res) {
            wx.showToast({
              title: '网络异常',
              icon: 'none'
            });
          });

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },

  // 刷新
  refreshTap() {
    this.getLocation();
    this.setData({
      flag: true
    })
    setTimeout(() => {
      this.setData({
        flag: false
      })
    }, 2000)
  },

  // 抽屉
  powerDrawer: function(e) {
    let currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    let animation = wx.createAnimation({
      duration: 200, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：x轴不偏移；
    animation.translateX(0).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function() {
      // 执行第二组动画：X轴偏移22px，停
      animation.translateX(240).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })

      //关闭抽屉
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },

  drawCredit: function() {
    const vm = this;

    // 圆弧半径
    const radius = this.data.canvasWidth * 3 / 12;
    // 内圆宽度
    const sweepInWidth = 10;
    // 外圆宽度
    const sweepOutWidth = 5;
    // 圆弧初始的弧度
    const startAngle = 0.82 * Math.PI;
    // 圆弧结束的弧度
    const endAngle = 2.18 * Math.PI;
    // 圆弧扫过的弧度
    const sweepAngle = Math.PI;
    // 空气数值
    let currentNum = vm.data.currentNum
    // 空气等级
    const creditLeverText = ["优", "优", "良", "轻度", "中度", "重度", "严重"];
    // 仪表盘的位置
    ctx.translate(this.data.canvasWidth / 2, this.data.canvasHeight * 3 / 5);
    // 画圆弧
    function drawRound() {
      // 保存画布
      ctx.save();
      // 画圆
      ctx.beginPath()
      // 设置画笔宽度
      ctx.setLineWidth(sweepOutWidth);
      // 设置画笔颜色
      ctx.setStrokeStyle('#dadada')
      // 画圆弧形，
      ctx.arc(0, 0, radius + 10, startAngle, endAngle);
      // 描绘路径边框
      ctx.stroke();
      // 还原画布
      ctx.restore();
    }

    //每个刻度间值
    let value = (endAngle - startAngle) / 6

    function drawIndicator() {
      ctx.save();
      let sweep = 0;
      let angleColor = ""
      if (currentNum <= 0) {
        sweep = 0;
        angleColor = "#009966"
      } else if (currentNum <= 50 && currentNum > 0) {
        sweep = (value / 50) * (currentNum + 1)
        angleColor = "#009966"
      } else if (currentNum > 50 && currentNum <= 100) {
        sweep = (value / 50) * (currentNum + 1)
        angleColor = "#ffde33"
      } else if (currentNum > 100 && currentNum <= 150) {
        sweep = (value / 50) * currentNum
        angleColor = "#ff9933"
      } else if (currentNum > 150 && currentNum <= 250) {
        sweep = ((value / 50) * 150) + ((value / 100) * (currentNum - 152))
        angleColor = "#cc0033"
      } else if (currentNum > 250 && currentNum <= 300) {
        sweep = ((value / 50) * 150) + ((value / 100) * 98) + ((value / 50) * (currentNum - 250))
        angleColor = "#660099"
      } else if (currentNum > 300 && currentNum <= 500) {
        sweep = ((value / 50) * 150) + ((value / 100) * 98) + ((value / 50) * 50) + ((value / 200) * (currentNum - 297))
        angleColor = "#7e0023"
      } else {
        sweep = ((value / 50) * 150) + ((value / 100) * 98) + ((value / 50) * 50) + ((value / 200) * 203)
        angleColor = "#7e0023"
      }

      ctx.beginPath()
      ctx.setStrokeStyle(angleColor)
      ctx.setLineWidth(sweepOutWidth);
      ctx.arc(0, 0, radius + 10, startAngle, startAngle + sweep);
      ctx.stroke()

      // 还原画布
      ctx.restore();
    }

    function drawCenterText() {
      ctx.save();
      ctx.beginPath();
      ctx.setTextAlign('center')

      // 绘制空气质量指数文字
      let content = "";
      // 绘制空气数值颜色
      let fsColor = "";
      if (currentNum <= 0) {
        content += creditLeverText[0];
        fsColor = "#009966";
      } else if (currentNum > 0 && currentNum <= 50) {
        content += creditLeverText[1];
        fsColor = "#009966";
      } else if (currentNum > 50 && currentNum <= 100) {
        content += creditLeverText[2];
        fsColor = "#ffde33";
      } else if (currentNum > 100 && currentNum <= 150) {
        content += creditLeverText[3];
        fsColor = "#ff9933";
      } else if (currentNum > 150 && currentNum <= 250) {
        content += creditLeverText[4];
        fsColor = "#cc0033";
      } else if (currentNum > 250 && currentNum <= 300) {
        content += creditLeverText[5];
        fsColor = "#660099";
      } else if (currentNum > 300 && currentNum <= 500) {
        content += creditLeverText[6];
        fsColor = "#7e0023";
      } else {
        content += creditLeverText[6];
        fsColor = "#7e0023";
      }



      // 绘制空气数值
      ctx.setFontSize(radius / 2)
      ctx.setFillStyle(fsColor)
      ctx.fillText(currentNum, 0, -radius / 10)

      // 绘制空气指数文字
      ctx.setFontSize(radius / 6)
      ctx.setFillStyle(fsColor)
      ctx.fillText(content, 0, radius / 4)

      //绘制PM空气质量指数
      ctx.setFontSize(11)
      ctx.setFillStyle('#aaaaaa')
      ctx.fillText("PM空气质量指数", 0, radius / 2)
      // 还原画布
      ctx.restore();

      // console.log("正在画画.....")
    }

    drawRound();
    drawIndicator();
    drawCenterText();
    ctx.draw()


  },
  // 通知
  notifyBLE: function(item) {
    let vm = this;
    // console.log(item);
    wx.notifyBLECharacteristicValueChange({
      deviceId: item.deviceId,
      serviceId: item.serviceId,
      characteristicId: item.characteristicId,
      state: true,
      success: function(res) {

        console.log('Notify Success:', res, item);
      },
      fail: function(res) {
        console.log('Notify Failed:', res, item);
      },
    });
  },

  getCharacteristics: function(deviceId, serviceId, callback) {
    console.log('get Services by deviceID:' + deviceId + ',serviceId:' + serviceId);
    let vm = this;
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: function(res) {
        console.log(res);
        for (let j = 0; j < res.characteristics.length; j++) {
          let charItem = res.characteristics[j];
          if (charItem.properties.notify) {
            let char = {
              deviceId: deviceId,
              serviceId: serviceId,
              characteristicId: charItem.uuid,
              read: charItem.properties.read,
              write: charItem.properties.write,
              notify: charItem.properties.notify,
            };
            // console.log(char);
            vm.notifyBLE(char);
          }
        }
      },
    })
  },

  // 获取BLE的service列表
  getServices: function(deviceId, callback) {
    console.log('get Services by deviceID:' + deviceId);
    let vm = this;
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function(res) {
        // console.log('读取到蓝牙服务', res);
        // vm.setData({services:res.services});
        for (let i = 0; i < res.services.length; i++) {
          let servicesItem = res.services[i];
          vm.getCharacteristics(deviceId, servicesItem.uuid);
        }
      },
    })
  },

  /**
   * 获取当前定位城市
   */
  getLocation: function() {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log(JSON.stringify(res))
        let latitude = res.latitude
        let longitude = res.longitude
        let speed = res.speed
        let accuracy = res.accuracy;
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: latitude,
            longitude: longitude
          },
          success: function(res) {
            // console.log(JSON.stringify(res));
            let province = res.result.ad_info.province
            let city = res.result.ad_info.city
            vm.setData({
              location: city
            });
            console.log(res, city);
            vm.updateWeather(city);
          },
          fail: function(res) {
            console.log('Fail Map request:', res);
          },
          complete: function(res) {
            // console.log(res);
          }
        });
      },
      fail: function(res) {
        // console.log('fail' + JSON.stringify(res))
      }
    })
  },
  /**
   * 更新天气信息
   */
  updateWeather: function(city) {
    let vm = this;
    ajax.requestPost(ajax.ajaxUrl() + 'index/index', {
      city: city,
    }, 'post', '', function(res) {
      console.log(res);
      if ('SUCCESS' === res.status) {
        let today = res.data.data.forecast[0];
        vm.setData({
          temperature: today.low.replace('低温 ', '') + '-' + today.high.replace('高温 ', ''),
          quality: res.data.data.quality,
          update_time: res.data.time,
          wind: today.fx + today.fl,
          outPM: res.data.data.pm25,
        })
      }
    }, function(res) {
      wx.showToast({
        title: '网络异常',
        icon: 'none'
      });
    });
  },
})